const fs = require('fs');
const readline  = require('readline');

let args = process.argv.splice(2);
if (args.length <= 0) {
    console.error("未输入源文件...");
}

let fileName = args[0];
let filePath = process.cwd() + "/" + fileName, newPath;

let regLine = "\r\n";         // 换行符
let regTit = /#+ /;
let regTitle = /^#+ .*$/;     // 标题识别
let regCode = /^```.*/;       // 代码块

/**
 * 获取标题级别，有几个 # 号就是第几集
 * @param line  当前行数据
 */
const getTitleLevel = (line) => {
    let level = 0;
    for (let j = 0; j < line.length; j++) {
        if (line.charAt(j) === '#') {
            level++;
        }
    }
    return level;
};

/**
 * 获取新的标题
 * @param line      当前行数据
 * @param level     当前标题的级别
 * @param titleNums 当前完整标题级别数组
 */
const getNewTitle = (line, level, titleNums) => {
    let lineArr = line.split(" ", 1);
    let str = "";
    for (let i = 0; i < level; i++) {
        str += "#";
    }
    str += " ";
    for (let i = 0; i < level; i++) {
        str += titleNums[i] + ".";
    }
    str += " ";
    str = line.replace(regTit, str);
    console.log(str);
    return str;
};

/**
 * 入口方法，读取文件并并逐行解析，判断是否为标题行，并将处理结果保存到新文件
 */
const analyze = () => {
    let content = fs.readFileSync(filePath, 'utf-8');
    let lines = content.split(regLine);

    let newContent = "";
    let isCode = false;
    let titleNums = [0, 0, 0, 0, 0, 0];

    for (let i = 0; i < lines.length; i++) {
        let line = lines[i];
        if (!line) {
            newContent += regLine;
            continue;
        }
        isCode = regCode.test(line) ? !isCode : isCode;
        if (!isCode && regTitle.test(line)) {
            let level = getTitleLevel(line);
            titleNums[level - 1] ++;
            for (let j = level; j < titleNums.length; j++) {
                titleNums[j] = 0;
            }
            newContent += getNewTitle(line, level, titleNums);
            newContent += regLine;
            continue;
        }
        newContent += line + regLine;
    }
    let dianIndex = filePath.lastIndexOf(".");
    newPath = filePath.substr(0, dianIndex) + "-copy" + filePath.substr(dianIndex);
    fs.writeFileSync(newPath, newContent);
};

console.info("---------------------------------------------")
console.info("开始解析原文件：" + filePath)
console.info("---------------------------------------------")
analyze();
console.info("---------------------------------------------")
console.info("新文件生成成功：" + newPath);
console.info("---------------------------------------------")

// console.info("----------------------------------")
// console.info("开始监听文件...");
// console.info("----------------------------------")
//
// let flag = false, prevMd5Key = null;
// fs.watch(filePath, (eventType, fileName) => {
//     if (flag) return;
//     flag = true;
//
//     let content = fs.readFileSync(filePath, 'utf-8');
//     let md5Key = md5(content);
//     if (md5Key === prevMd5Key) {
//         flag = false;
//         return;
//     }
//     console.log("文件发生变化");
//     console.info("----------------------------------")
//
//     prevMd5Key = md5Key;
//
//     setTimeout(() => {
//         analyze(content, fileName);
//     }, 300);
//     setTimeout(() => {
//         flag = false;
//     }, 1000);
// });